package com.emm.yixun.mobile.ui.powertochoose;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.mobile.R;
import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.base.BaseActivity;
import com.emm.yixun.mobile.model.GetCallBack;
import com.emm.yixun.mobile.ui.customer.FollowUpActivity;
import com.emm.yixun.mobile.ui.powertochoose.SelectPhoneActivity.GetUserCallList.UserCallList;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import xf.tools.Loading;

/**
 * 
 * <p>
 * <b>Title：</b> 选择电话拨打接界面
 * </p>
 * <p>
 * <b>Description：</b>
 * </p>
 * 
 * @author tangxin
 * @date 2016年12月6日 下午4:16:24
 */

public class SelectPhoneActivity extends BaseActivity {
	public static final String TAG = "SelectPhoneActivity";

	RelativeLayout select_phone_bg;

	LinearLayout down_none;

	ListView phone_list;

	TextView sure_btn;

	TextView cancel;

	private String terminalModel = "0";

	private String customerId = "";

	private String phonenumber = "";

	String caller;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.select_phone_activity);
		BaseActivity.activity = this;

		phonenumber = getIntent().getStringExtra("phonenumber");
		customerId = getIntent().getStringExtra("customerId");
		Log.v(TAG, "phonenumber:" + phonenumber);
		Log.v(TAG, "terminalModelId:" + customerId);

		InitView();

		InitBtn();

		getUserCallList();
	}

	@Override
	protected void onResume() {
		super.onResume();
		BaseActivity.activity = this;
	}

	private void InitView() {
		select_phone_bg = (RelativeLayout) findViewById(R.id.select_phone_bg);
		down_none = (LinearLayout) findViewById(R.id.down_none);
		phone_list = (ListView) findViewById(R.id.phone_list);
		sure_btn = (TextView) findViewById(R.id.sure_btn);
		cancel = (TextView) findViewById(R.id.cancel);
	}

	private void InitBtn() {
		select_phone_bg.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		down_none.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.v(TAG, "drop_none");
			}
		});
		phone_list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				caller = getUserCallList.getUserCallList().get(position).getTelePhone();
				adapter.selecttype(position);
			}
		});
		sure_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 确定
				getCallBack(caller);
			}
		});
		cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	public static class GetUserCallList {

		private String result;// 返回码
		private String errorCode;// 错误代码
		private String errorMsg;// 错误信息
		private String isPhoneInformation;// 【是否已开通电话平台：0、未开通；1、已开通】

		public String getIsPhoneInformation() {
			return isPhoneInformation;
		}

		public void setIsPhoneInformation(String isPhoneInformation) {
			this.isPhoneInformation = isPhoneInformation;
		}

		ArrayList<UserCallList> userCallList;

		public String getResult() {
			return result;
		}

		public void setResult(String result) {
			this.result = result;
		}

		public String getErrorCode() {
			return errorCode;
		}

		public void setErrorCode(String errorCode) {
			this.errorCode = errorCode;
		}

		public String getErrorMsg() {
			return errorMsg;
		}

		public void setErrorMsg(String errorMsg) {
			this.errorMsg = errorMsg;
		}

		public ArrayList<UserCallList> getUserCallList() {
			return userCallList;
		}

		public void setUserCallList(ArrayList<UserCallList> userCallList) {
			this.userCallList = userCallList;
		}

		public static class UserCallList {// （用户电话列表）
			private String telePhoneType;// 电话类型
			private String telePhone;// 电话

			public String getTelePhoneType() {
				return telePhoneType;
			}

			public void setTelePhoneType(String telePhoneType) {
				this.telePhoneType = telePhoneType;
			}

			public String getTelePhone() {
				return telePhone;
			}

			public void setTelePhone(String telePhone) {
				this.telePhone = telePhone;
			}

			private boolean selecttype = false;

			public boolean isSelecttype() {
				return selecttype;
			}

			public void setSelecttype(boolean selecttype) {
				this.selecttype = selecttype;
			}
		}

	}

	PhoneSelectAdapter adapter;

	class PhoneSelectAdapter extends BaseAdapter {

		ArrayList<UserCallList> lists;

		public PhoneSelectAdapter(ArrayList<UserCallList> lists) {
			this.lists = lists;
		}

		public void selecttype(int select) {
			for (int i = 0; i < lists.size(); i++) {
				lists.get(i).setSelecttype(false);
			}
			lists.get(select).setSelecttype(true);
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			return null == lists ? 0 : lists.size();
		}

		@Override
		public Object getItem(int position) {
			return null == lists ? null : lists.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHoudlerPhoneSelect v = null;
			if (null == convertView) {
				convertView = LayoutInflater.from(SelectPhoneActivity.this).inflate(R.layout.select_adapter_item, null);
				v = new ViewHoudlerPhoneSelect();
				v.content = (TextView) convertView.findViewById(R.id.content);
				v.select_icon = (ImageView) convertView.findViewById(R.id.select_icon);
				convertView.setTag(v);
			} else {
				v = (ViewHoudlerPhoneSelect) convertView.getTag();
			}
			if (lists.get(position).isSelecttype()) {
				v.select_icon.setImageResource(R.drawable.ico_selt);
			} else {
				v.select_icon.setImageResource(R.drawable.ico_delt_no);
			}
			if ("1".equals(lists.get(position).getTelePhoneType())) {// 1手机 2座机
				v.content.setText("手机 【" + lists.get(position).getTelePhone() + "】");
			} else {
				v.content.setText("固话 【" + lists.get(position).getTelePhone() + "】");
			}
			return convertView;
		}
	}

	public static class ViewHoudlerPhoneSelect {
		ImageView select_icon;
		TextView content;
	}

	GetCallBack getCallBack;

	/**
	 * @param caller
	 *            主叫
	 */
	private void getCallBack(String caller) {
		EmmApplication.updateUrl("getCallBack");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("caller", caller);
		map.put("version", EmmApplication.getPackageManager(5));
		map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
		map.put("token", EmmApplication.getToken());
		map.put("userId", EmmApplication.getUserId());
		map.put("terminalCode", EmmApplication.getPackageManager(2));
		map.put("projectCode", EmmApplication.getProjectCode());
		map.put("customerId", customerId);
		map.put("terminalModel", terminalModel);
		map.put("terminalModelId", customerId);
		map.put("projectId", EmmApplication.getProjectID());
		map.put("called", phonenumber);
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("params", map);
		JSONObject json = new JSONObject(paramsMap);
		String jsonstr = json.toString();
		RequestParams params = new RequestParams();
		params.put("body", jsonstr);
		Log.v("distributionConsultant-->post", EmmApplication.urlStr + "?body=" + jsonstr);
		AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
		asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
			@Override
			public void onFailure(Throwable error, String content) {
				super.onFailure(error, content);
				Loading.hideDialogForLoading();
				Log.v(TAG, "请求结束error:" + error + "==" + content);
			}

			@Override
			public void onFinish() {
				Loading.hideDialogForLoading();
				Log.v(TAG, "请求结束");
				super.onFinish();
			}

			@Override
			public void onStart() {
				super.onStart();
				Loading.showDialogForLoading(SelectPhoneActivity.this, "正在加载...", false, true, 60000);
				Log.v(TAG, "请求开始");
			}

			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				if (content == null) {
					return;
				}
				Log.v("content", content);
				JSONObject jsonObj = JSONObject.parseObject(content);
				JSONObject resData = (JSONObject) jsonObj.get("resData");
				if (resData == null) {
					Log.v(TAG, "信息返回值为空");
					return;
				}

				getCallBack = JSONObject.parseObject(resData.toString(), GetCallBack.class);
				if ("1".equals(getCallBack.getResult())) {
					Log.v(TAG, "followId:" + getCallBack.getFollowId());
					Intent intent = new Intent(SelectPhoneActivity.this, FollowUpActivity.class);
					intent.putExtra("FollowId", getCallBack.getFollowId());
					intent.putExtra("customerId", customerId);
					startActivity(intent);
					finish();
				} else {
					EmmApplication.T2(getCallBack.getErrorMsg().toString());
					try {
						Log.v("获取失败", "errorCode:" + getCallBack.getErrorCode().toString() + "errorMsg:"
								+ getCallBack.getErrorMsg().toString());
					} catch (NullPointerException e) {
						Log.v("distribution", "错误信息获取空指针异常");
					}
				}
			}
		});
	}

	/**
	 * 查询用户电话列表接口
	 **/
	GetUserCallList getUserCallList;

	private void getUserCallList() {
		EmmApplication.updateUrl("getUserCallList");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("token", EmmApplication.getToken());
		map.put("userId", EmmApplication.getUserId());
		map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
		map.put("terminalCode", EmmApplication.getPackageManager(2));
		map.put("version", EmmApplication.getPackageManager(5));
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("params", map);
		JSONObject json = new JSONObject(paramsMap);
		String jsonstr = json.toString();
		RequestParams params = new RequestParams();
		params.put("body", jsonstr);
		Log.v("distributionConsultant-->post", EmmApplication.urlStr + "?body=" + jsonstr);
		AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
		asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
			@Override
			public void onFailure(Throwable error, String content) {
				super.onFailure(error, content);
				Loading.hideDialogForLoading();
				Log.v(TAG, "请求结束error:" + error + "==" + content);
				finish();
			}

			@Override
			public void onFinish() {
				Loading.hideDialogForLoading();
				Log.v(TAG, "请求结束");
				super.onFinish();
			}

			@Override
			public void onStart() {
				super.onStart();
				Loading.showDialogForLoading(SelectPhoneActivity.this, "正在加载...", false, true, 60000);
				Log.v(TAG, "请求开始");
			}

			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				if (content == null) {
					return;
				}
				Log.v("content", content);
				JSONObject jsonObj = JSONObject.parseObject(content);
				JSONObject resData = (JSONObject) jsonObj.get("resData");
				if (resData == null) {
					Log.v(TAG, "信息返回值为空");
					return;
				}

				getUserCallList = JSONObject.parseObject(resData.toString(), GetUserCallList.class);
				if ("1".equals(getUserCallList.getResult())) {
					if ("0".equals(getUserCallList.getIsPhoneInformation())) {// 未开通
						Intent intent = new Intent(Intent.ACTION_DIAL);
						Uri data = Uri.parse("tel:" + phonenumber);
						intent.setData(data);
						intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						startActivity(intent);
						finish();
					} else {
						if (null != getUserCallList && null != getUserCallList.getUserCallList()) {
							down_none.setVisibility(View.VISIBLE);
							select_phone_bg.setBackgroundColor(Color.parseColor("#05000000"));
							caller = getUserCallList.getUserCallList().get(0).getTelePhone();
							adapter = new PhoneSelectAdapter(getUserCallList.getUserCallList());
							phone_list.setAdapter(adapter);
							adapter.selecttype(0);
						} else {
							EmmApplication.T2("用户电话列表为空");
							select_phone_bg.setBackgroundColor(Color.parseColor("#00000000"));
							down_none.setVisibility(View.GONE);
							finish();
							Log.v(TAG, "没有查询到用户电话列表");
						}
					}
				} else {
					EmmApplication.T2(getUserCallList.getErrorMsg().toString());
					finish();
					Log.v(TAG, "没有查询到用户电话列表");
					try {
						Log.v("获取失败", "errorCode:" + getUserCallList.getErrorCode().toString() + "errorMsg:"
								+ getUserCallList.getErrorMsg().toString());
					} catch (NullPointerException e) {
						Log.v("distribution", "错误信息获取空指针异常");
					}
				}
			}
		});
	}
}
